package activity.addCamera;

import android.content.Intent;
import android.graphics.drawable.Animatable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.hichip.campro.R;
import com.hichip.tools.HiSearchSDK;
import com.hichip.tools.HiSinVoiceData;
import com.hichip.tools.HiSmartWifiSet;

import base.HiActivity;
import bean.MyCamera;
import butterknife.BindView;
import common.HiDataValue;
import common.TitleView;
import custom.dialog.NiftyDialogBuilder;
import main.MainActivity;
import utils.HiToast;
import utils.HiTools;

/**
 * 声波配置
 * Created by lt on 2018\3\8 0008.
 */
public class SoundWavesConfigActivity extends HiActivity implements View.OnClickListener {

    @BindView(R.id.title) TitleView title;
    @BindView(R.id.tv_uid) TextView tv_uid;
    @BindView(R.id.tv_hint_pause_send) TextView tv_hint_pause_send;
    @BindView(R.id.tv_hava_uid) TextView tv_hava_uid;
    @BindView(R.id.but_search_device) Button but_search_device;
    @BindView(R.id.tv_count_down) TextView tv_count_down;
    @BindView(R.id.iv_wave) ImageView iv_wave;
    @BindView(R.id.iv_dividing) ImageView iv_dividing;


    private String mUid;
    private String mSSID;
    private String mPsw;
    private HiSinVoiceData sv;
    private boolean isSending = false;//是否 发送中...   否则是暂停
    private boolean mIsReset = false;
    private NiftyDialogBuilder dialog;
    private Animatable animatable;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_soundwaves_config;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        getIntentData();
        initViewAndData();
        setListeners();
    }

    private void getIntentData() {
        mUid = getIntent().getStringExtra(HiDataValue.EXTRAS_KEY_UID);
        mSSID = getIntent().getStringExtra("ssid");
        mPsw = getIntent().getStringExtra("psw");
        mIsReset = getIntent().getBooleanExtra("reset", false);
    }

    private void setListeners() {
        but_search_device.setOnClickListener(this);
    }

    private void initViewAndData() {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        tv_hava_uid.setVisibility(TextUtils.isEmpty(mUid) ? View.GONE : View.VISIBLE);
        but_search_device.setVisibility(TextUtils.isEmpty(mUid) ? View.VISIBLE : View.GONE);
        iv_dividing.setVisibility(TextUtils.isEmpty(mUid) ? View.VISIBLE : View.GONE);
        title.setTitle(getString(R.string.title_sound_config));
        title.setButton(TitleView.NAVIGATION_BUTTON_LEFT);
        title.setRightTxtBack(R.mipmap.x_bule);
        title.setNavigationBarButtonListener(new TitleView.NavigationBarButtonListener() {
            @Override
            public void OnNavigationButtonClick(int which) {
                switch (which) {
                    case TitleView.NAVIGATION_BUTTON_LEFT:
                        SoundWavesConfigActivity.this.finish();
                        break;
                    case TitleView.NAVIGATION_BUTTON_IV_RIGHT:
                        Intent intent=new Intent(SoundWavesConfigActivity.this,MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent,true);
                        break;
                }
            }
        });

        if (!TextUtils.isEmpty(mUid)) {
            tv_uid.setText(mUid);
        }

        sv = new HiSinVoiceData(SoundWavesConfigActivity.this);
        if (mSSID == null || mSSID == null) {
            HiToast.showToast(SoundWavesConfigActivity.this, getString(R.string.data_error));
            finish();
            return;
        }
        // wifi一键配置的api
        HiSmartWifiSet.HiStartSmartConnection(mSSID, mPsw, (byte) 4);
        sv.setValue(mSSID, mPsw);
        sv.startSinVoice();
        but_search_device.setEnabled(false);
        timer.start();
        mCountDownTimer.start();
        isSending = true;

        //播放帧动画
        animatable = (Animatable) iv_wave.getDrawable();
        animatable.start();
    }

    private HiSearchSDK searchSDK = new HiSearchSDK(new HiSearchSDK.ISearchResult() {
        @Override
        public void onReceiveSearchResult(HiSearchSDK.HiSearchResult result) {
            String temp = result.uid.substring(0, 4);
            if (!TextUtils.isEmpty(temp)) {
                Message msg = mHandler.obtainMessage();
                msg.obj = result;
                msg.what = HiDataValue.HANDLE_MESSAGE_SCAN_RESULT;
                mHandler.sendMessage(msg);
            }
        }
    });

    private int mCountDownTime = 61;// 60秒倒计时

    private CountDownTimer mCountDownTimer = new CountDownTimer(mCountDownTime * 1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            if (millisUntilFinished > 0) {
                if (millisUntilFinished / 1000 == 30) {
                    but_search_device.setEnabled(true);
                }
                tv_count_down.setText((millisUntilFinished / 1000) + "");
            }
        }

        @Override
        public void onFinish() {
            if (TextUtils.isEmpty(mUid)) {
                Intent intent = new Intent(SoundWavesConfigActivity.this, LANSearchCameraActivity.class);
                intent.putExtra("type", 4);
                startActivity(intent);
            } else {
                if (animatable != null) {
                    animatable.stop();
                }
                if (timer != null) {
                    timer.cancel();
                }
                if (searchSDK != null) {
                    searchSDK.stop();
                }
                HiSmartWifiSet.HiStopSmartConnection();
                sv.stopSinVoice();

                View customView = View.inflate(SoundWavesConfigActivity.this, R.layout.pup_sound_wave_fail, null);
                PopupWindow popupWindow = new PopupWindow(customView);
                ColorDrawable cd = new ColorDrawable(-000);
                popupWindow.setBackgroundDrawable(cd);
                popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
                popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
                popupWindow.setFocusable(true);
                popupWindow.showAtLocation(customView, Gravity.CENTER, 0, 0);

                //SSID
                TextView tv_ssid = customView.findViewById(R.id.tv_ssid);
                tv_ssid.setText(getString(R.string.wireless_name) + mSSID);

                //密码
                TextView tv_password = customView.findViewById(R.id.tv_password);
                tv_password.setText(getString(R.string.password_colon) + mPsw);

                //重新尝试
                TextView tv_try = customView.findViewById(R.id.tv_try);
                tv_try.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                        Intent intent = new Intent(SoundWavesConfigActivity.this, SeleApOrSoundwaveActivty.class);
                        startActivity(intent);
                    }
                });

                //修改WiFi密码
                TextView tv_pup_modify = customView.findViewById(R.id.tv_pup_modify);
                tv_pup_modify.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        popupWindow.dismiss();
                        handModify(tv_pup_modify);
                    }
                });

            }
        }
    };

    private CountDownTimer timer = new CountDownTimer(60000, 5000) {
        @Override
        public void onTick(long millisUntilFinished) {
            if (!TextUtils.isEmpty(mUid)) {
                searchSDK.stop();
                searchSDK.search2();
            }
        }

        @Override
        public void onFinish() {
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        if (timer == null) {
            timer = new CountDownTimer(60000, 6000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    searchSDK.stop();
                    searchSDK.search2();
                }

                @Override
                public void onFinish() {
                }
            };
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        HiSmartWifiSet.HiStopSmartConnection();
        if (sv != null) {
            sv.stopSinVoice();
        }
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
        searchSDK.stop();
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.but_search_device://去搜索设备
                if (HiTools.isWifiConnected(SoundWavesConfigActivity.this)) {
                    Intent intent = new Intent(SoundWavesConfigActivity.this, LANSearchCameraActivity.class);
                    intent.putExtra("type", 4);
                    intent.putExtra("category", 2);// 点击已听见设备发出配置,LANSearchCameraActivity 里面失败提示不一样，少一个上电
                    if (!TextUtils.isEmpty(mUid)) {
                        intent.putExtra(HiDataValue.EXTRAS_KEY_UID, mUid);
                    }
                    startActivity(intent);
                } else {
                    HiToast.showToast(SoundWavesConfigActivity.this, getString(R.string.toast_connect_wifi));
                }

                break;
        }
    }

    // 点击修改WiFi信息
    private void handModify(View view) {
        View customView = View.inflate(SoundWavesConfigActivity.this, R.layout.pup_sound_wave_wifi, null);
        PopupWindow popupWindow = new PopupWindow(customView);
        ColorDrawable cd = new ColorDrawable(-0000);
        popupWindow.setBackgroundDrawable(cd);
        popupWindow.setOutsideTouchable(false);
        popupWindow.setFocusable(true);
        popupWindow.setWidth(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.setHeight(WindowManager.LayoutParams.MATCH_PARENT);
        popupWindow.showAtLocation(view, Gravity.CENTER, 0, 0);

        TextView tv_ssid = customView.findViewById(R.id.tv_ssid);
        EditText et_psw = customView.findViewById(R.id.et_psw);

        tv_ssid.setText(mSSID);
        et_psw.setText(mPsw);

        //取消
        TextView tv_cancel = customView.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        //确认修改
        TextView tv_ok = customView.findViewById(R.id.tv_ok);
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String ssid = tv_ssid.getText().toString();
                String psw = et_psw.getText().toString();
                if (TextUtils.isEmpty(ssid)) {
                    HiToast.showToast(SoundWavesConfigActivity.this, getString(R.string.ssid_not_empty));
                    return;
                }
                popupWindow.dismiss();
                mSSID = ssid;
                mPsw = psw;

                mCountDownTime = 61;
                but_search_device.setEnabled(false);
                if (timer != null) {
                    timer.cancel();
                }
                if (mCountDownTimer != null) {
                    mCountDownTimer.cancel();
                }
                if (animatable != null && !animatable.isRunning()) {
                    animatable.start();
                }
                timer.start();
                mCountDownTimer.start();
                Log.i("tedu","--999-mSSID-:"+mSSID+"--mPsw--:"+mPsw);
                HiSmartWifiSet.HiStartSmartConnection(mSSID, mPsw, (byte) 4);
                Log.i("tedu","--999-startSinVoice--mSSID-:"+mSSID+"--mPsw--:"+mPsw);
                //sv = new HiSinVoiceData(SoundWavesConfigActivity.this);
                sv.setValue(mSSID, mPsw);
                sv.startSinVoice();
            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case HiDataValue.HANDLE_MESSAGE_SCAN_RESULT:
                    HiSearchSDK.HiSearchResult searchResult = (HiSearchSDK.HiSearchResult) msg.obj;
                    if (!TextUtils.isEmpty(searchResult.uid)) {
                        if (searchResult.uid.equals(mUid)) {
                            if (mIsReset) {
                                HiToast.showToast(SoundWavesConfigActivity.this, getString(R.string.config_net_success));
                                Intent broadcast = new Intent();
                                broadcast.setAction(HiDataValue.ACTION_CAMERA_INIT_END);
                                sendBroadcast(broadcast);
                                Intent intent = new Intent(SoundWavesConfigActivity.this, MainActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(intent);
                            } else {
                                for(MyCamera camera:HiDataValue.CameraList){
                                    if(camera.getUid().equalsIgnoreCase(mUid)){
                                        Intent broadcast = new Intent();
                                        broadcast.putExtra("mIsAdd", true);
                                        broadcast.setAction(HiDataValue.ACTION_CAMERA_INIT_END);
                                        sendBroadcast(broadcast);
                                        Intent intent=new Intent(SoundWavesConfigActivity.this,MainActivity.class);
                                        startActivity(intent);
                                        HiToast.showToast(SoundWavesConfigActivity.this, getString(R.string.config_net_success));
                                        return;
                                    }
                                }
                                Intent intent = new Intent(SoundWavesConfigActivity.this, AddCameraActivity.class);
                                intent.putExtra(HiDataValue.EXTRAS_KEY_UID, mUid);
                                intent.putExtra("type", 1);
                                startActivity(intent);

                            }
                        }
                    }
                    break;
            }
        }
    };
}
